package com.marver.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间工具类
 * @ClassName: DateUtils 
 * @date 2016年2月23日 下午2:34:19
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {

	/**
	 * 获取两个日期之间的天数
	 *
	 * @param before
	 * @param after
	 * @return
	 */
	public static double getDistanceOfTwoDate(Date before, Date after) {
		long beforeTime = before.getTime();
		long afterTime = after.getTime();
		return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
	}

    /**
     * 将时间格式字符串转化成时间 ，例如：yyyy-MM-dd HH:mm:ss
     * @return 
     */
    public static Date string2Date(String dateStr,String fomat){
        SimpleDateFormat formatter = new SimpleDateFormat(fomat);
        Date s = null;
        try {  
             s = formatter.parse(dateStr);
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return s;  
    }

	/**
	 * 将时间转换为字符串 例如：yyyy-MM-dd HH:mm:ss
	 * @param date
	 * @return
	 */
	public static String date2String(Date date,String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		String dateString = formatter.format(date);
		return dateString;
	}

	/**
	 * 根据一个字符串形式的日期，返回是星期1,2,3。。。的字符串
	 *
	 * @param date
	 * @return
	 */
	public static int getWeek(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int week = c.get(Calendar.DAY_OF_WEEK);
		// hour中存的就是星期几了，其范围 1~7
		// 1=星期日 7=星期六，其他类推
		return week;
	}

	/**
	 * 根据一个字符串形式的日期，返回是星期1,2,3。。。的字符串
	 *
	 * @param date
	 * @return
	 */
	public static int getCWeek(Date date) {
		int w = getWeek(date);
		if(w==1) return 7;
		w--;
		return w;
	}

	/**
	 * 根据一个字符串形式的日期，返回是星期1,2,3。。。的字符串
	 *
	 * @param sdate
	 * @return
	 */
	public static String getWeek(String sdate) {
		// 再转换为时间
		Date date = DateUtils.string2Date(sdate,"yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		// int hour=c.get(Calendar.DAY_OF_WEEK);
		// hour中存的就是星期几了，其范围 1~7
		// 1=星期日 7=星期六，其他类推
		return new SimpleDateFormat("EEEE").format(c.getTime());
	}

	/**
	 * 根据一个字符串形式的日期，返回是星期一、二、三...的字符串
	 *
	 * @param sdate
	 * @return
	 */
	public static String getWeekStr(String sdate) {
		String str = "";
		str = DateUtils.getWeek(sdate);
		if ("1".equals(str)) {
			str = "星期日";
		} else if ("2".equals(str)) {
			str = "星期一";
		} else if ("3".equals(str)) {
			str = "星期二";
		} else if ("4".equals(str)) {
			str = "星期三";
		} else if ("5".equals(str)) {
			str = "星期四";
		} else if ("6".equals(str)) {
			str = "星期五";
		} else if ("7".equals(str)) {
			str = "星期六";
		}
		return str;
	}

	public static Date dateAddDays(String date,String format, int addDays) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return dateAddDays(sdf.parse(date),1);
	}
	
	/**
	 * 时间增加一天
	 * @param date
	 * @param addDays
	 * @return
	 */
	public static Date dateAddDays(Date date, int addDays) {
		if (date == null)
			return null;
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, addDays);
		return cal.getTime();
	}
	/**
	 * 时间增加一月
	 * @param date
	 * @param addMonths
	 * @return
	 */
	public static Date dateAddMonths(Date date, int addMonths) {
		if (date == null)
			return null;
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.MONTH, addMonths);
		return cal.getTime();
	}

	/**
	 * 时间增加一年
	 * @param date
	 * @param addYears
	 * @return
	 */
	public static Date dateAddYears(Date date, int addYears) {
		if (date == null)
			return null;
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.YEAR, addYears);
		return cal.getTime();
	}

	/**
	 * 计算天的开始时间(2006-08-02 00:00:00)
	 *
	 * @param when
	 * @return
	 */
	public static Date getStartOfDay(Date when) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(when);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		return cal.getTime();
	}

	/**
	 * 计算天的结束时间(2006-08-02 23:59:59)
	 *
	 * @param when
	 * @return
	 */
	public static Date getEndOfDay(Date when) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(getStartOfDay(when));
		cal.add(Calendar.DATE, 1);
		cal.add(Calendar.SECOND, -1);
		return cal.getTime();
	}

	/**
	 * 获取昨天日期
	 * @return
	 */
	public static String getYesterday(){
		Calendar   cal   =   Calendar.getInstance();
		cal.add(Calendar.DATE,   -1);
		return date2String(cal.getTime(),"yyyy-MM-dd");
	}

	//=================项目专属

	/**
	 * 日期字符格式化 -> yyyyMMdd
	 * @param dateStr
	 * @return
	 */
	public static String formatString(String dateStr){
		return date2String(string2Date(dateStr,"yyyy-MM-dd"),"yyyyMMdd");
	}
	/**
	 * 日期字符格式化成int类型 -> yyyyMMdd
	 * @param dateStr
	 * @return
	 */
	public static Integer stringFormat2Int(String dateStr){
		return Integer.valueOf(date2String(string2Date(dateStr,"yyyy-MM-dd"),"yyyyMMdd"));
	}
	/**
	 * 日期格式化成int类型 -> yyyyMMdd
	 * @param date
	 * @return
	 */
	public static Integer dateFormat2Int(Date date){
		return Integer.valueOf(date2String(date,"yyyyMMdd"));
	}

	
	public static String getCurrDate(){
		return new SimpleDateFormat("yyyy-MM-dd").format(new Date());//获取当前时间
	}
	
	public static String getCurrTime(){
		return (new SimpleDateFormat("HH:mm:ss")).format(new Date());  
	}
	
	public static String getCurrDateTime(){
		return (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());  
	}
	
	/**
	 * 比较开始和结束时间的大小
	 * @param startTime
	 * @param endTime
	 * @return
	 * 		0: startTime等于endTime;
	 * 		1: startTime大于endTime;
	 * 		2: startTime小于endTime;
	 */
	public static int compare(Object beginTime, Object endTime,String format) {
		if (beginTime == null || StringUtils.isBlank(beginTime.toString())
				|| endTime == null || StringUtils.isBlank(endTime.toString())) {
			throw new RuntimeException("传入日期为空！");
		}
		int reuslt=0;
		if(format==null||format.isEmpty()){
			format="yyyy-MM-dd";
		}
		try {

			Date start = new SimpleDateFormat(format).parse(beginTime.toString());
			Date end = new SimpleDateFormat(format).parse(endTime.toString());
			if(start.getTime() > end.getTime()){
				reuslt=1;
			}else if(start.getTime() < end.getTime()){
				reuslt=2;
			}
			return reuslt;
		} catch (Exception e) {
			throw new RuntimeException("转换日期出错！");
		}
	}
	
	/**
	 * 判断time是否在startTime和endTime时间段内
	 * @param startTime
	 * @param time
	 * @param endTime
	 * @return  false 否，true 是
	 */
	public static boolean compare(Object beginTime,Object time, Object endTime,String format) {
		if (beginTime == null || StringUtils.isBlank(beginTime.toString())
				|| time == null || StringUtils.isBlank(time.toString())
				|| endTime == null || StringUtils.isBlank(endTime.toString())) {
			throw new RuntimeException("传入日期为空！");
		}
		if(format==null||format.isEmpty()){
			format="yyyy-MM-dd HH:mm:ss";
		}
		try {
			Date start = new SimpleDateFormat(format).parse(beginTime.toString());
			Date b = new SimpleDateFormat(format).parse(time.toString());
			Date end = new SimpleDateFormat(format).parse(endTime.toString());
			if(start.getTime()<=b.getTime() && b.getTime()<=end.getTime()){
				return true;
			}
			return false;
		} catch (Exception e) {
			throw new RuntimeException("转换日期出错！");
		}
	}
	
	/**
	 * 时间计算
	 * @param date 格式：yyyy-MM-dd HH:mm:ss
	 * @param unit 1表示秒，2表示分钟，3表示时，4表示天
	 * @param addnum 正数表示增加，负数表示减少
	 * @return
	 */
	public static String dateTimeDiff(String date1,int unit,int addnum){
		if(date1 == null || StringUtils.isBlank(date1)){
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		int second=0;
		switch(unit){
			case 1:
				second=addnum;
				break;
			case 2:
				second=60*addnum;
				break;
			case 3:
				second=60*60*addnum;
				break;	
			case 4:
				second=24*60*60*addnum;
				break;					
			default:
				second=0;
			    break;	
		}
		try {
			Date date = sdf.parse(date1.toString());
	        Calendar calendar = Calendar.getInstance();
	        calendar.setTime(date);
	        calendar.add(Calendar.SECOND,second);	        
//			long time=(date.getTime()/1000)+second;
//			date.setTime(time);
			return sdf.format(calendar.getTime());
		} catch (Exception e) {
			throw new RuntimeException("转换日期出错！"+date1);
		}
	}
	
	/**
	 * 计算两个日期间相差的秒数
	 * @param date1 格式：yyyy-MM-dd HH:mm:ss
	 * @param date2 格式：yyyy-MM-dd HH:mm:ss
	 * @return
	 * @throws Exception 
	 */
	public static long getTwoDateBySecond(String date1,String date2){
		if(date1 == null || StringUtils.isBlank(date1)
				||date2 == null || StringUtils.isBlank(date2)){
			throw new RuntimeException("参数为空！date1="+date1+",date2="+date2);
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date d1 = sdf.parse(date1.toString());
	        Calendar c1 = Calendar.getInstance();
	        c1.setTime(d1);
	        Date d2 = sdf.parse(date2.toString());
	        Calendar c2 = Calendar.getInstance();
	        c2.setTime(d2);
			return (c2.getTimeInMillis()-c1.getTimeInMillis())/1000;
		} catch (Exception e) {
			throw new RuntimeException("转换日期出错！date1="+date1+",date2="+date2);
		}
	}	

	public static long getMillisecond(String date,String format){
		if(StringUtils.isEmpty(format))format="yyyy-MM-dd HH:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			Date d1 =sdf.parse(date);
			Calendar c1 = Calendar.getInstance();
			c1.setTime(d1);
			return c1.getTimeInMillis();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException("转换日期出错！date="+date);
		}
	}
//	public static void main(String[] args) throws ParseException {
//		System.out.println(DateUtils.date2String(DateUtils.dateAddDays("20180206", "yyyyMMdd", 1),"yyyyMMdd"));
//		//System.out.println(DateUtils.stringFormat2Int("20170802"));
//	}
}
